import 'package:flutter/widgets.dart';

/// Used to configure the [Condition] Widget by providing an [expression] and
/// a [builder]. [Condition] will show the provided [builder] when the
/// [expression] results in true.
class DxIf {
  final bool expression;
  final Widget Function() builder;

  DxIf(this.expression, this.builder);
}

/// Used to configure the [SwitchCondition] [Widget].
/// The [DxCase] will be compared to the [DxCase] of the [SwitchCondition].
/// If the values are equal the provided [builder] will be shown.
class DxCase<T> {
  final T value;
  final Widget Function() builder;

  DxCase(this.value, this.builder);
}

/// 解决在视图中if .. else if .. else问题
/// github地址：https://github.com/SEGVeenstra/conditioned
class DxCondition extends StatelessWidget {
  final List<DxIf> ifList;

  DxCondition({
    super.key,
    required this.ifList,
    Widget Function()? elseBuilder,
  }) {
    elseBuilder ??= () => const SizedBox.shrink();
    ifList.add(DxIf(true, elseBuilder));
  }

  DxCondition.bool(
    bool condition, {
    super.key,
    required Widget Function() trueBuilder,
    Widget Function()? falseBuilder,
  }) : ifList = [] {
    falseBuilder ??= () => const SizedBox.shrink();
    ifList.add(DxIf(condition, trueBuilder));
    ifList.add(DxIf(!condition, falseBuilder));
  }

  static DxCondition when<T>(
    T value, {
    required List<DxCase<T>> caseList,
    Widget Function()? defaultBuilder,
  }) {
    defaultBuilder ??= () => const SizedBox.shrink();
    final newCases = caseList.map((c) => DxIf(value == c.value, () => c.builder())).toList();
    return DxCondition(ifList: newCases, elseBuilder: defaultBuilder);
  }

  @override
  Widget build(BuildContext context) {
    for (var c in ifList) {
      if (c.expression) return c.builder();
    }
    throw ArgumentError('There was no valid result.');
  }
}
